<template>
  <div class="group-bargaining">
    <a-row>
      <a-col :span="8">
        <a-carousel class="group-bargaining-carousel" autoplay>
          <template v-if="type == 1">
            <div>
              <img src="~@images/groupBargaining/general_01.png" alt="" />
            </div>
            <div>
              <img src="~@images/groupBargaining/general_02.png" alt="" />
            </div>
            <div>
              <img src="~@images/groupBargaining/general_03.png" alt="" />
            </div>
          </template>
          <template v-else-if="type == 2">
            <div>
              <img src="~@images/groupBargaining/inerratic_01.png" alt="" />
            </div>
            <div>
              <img src="~@images/groupBargaining/inerratic_02.png" alt="" />
            </div>
            <div>
              <img src="~@images/groupBargaining/inerratic_03.png" alt="" />
            </div>
          </template>
        </a-carousel>
      </a-col>
      <a-col :span="16">
        <a-form-model
          class="group-bargaining-form"
          ref="ruleForm"
          :model="formData"
          :rules="rules"
          :label-col="{ span: 4 }"
          :wrapper-col="{ span: 20 }"
        >
          <div class="form-title">基础设置：</div>
          <a-form-model-item prop="name">
            <template slot="label">
              <span style="color: red">*</span>活动名称
            </template>
            <a-input
              :maxLength="20"
              allow-clear
              style="width: 200px"
              v-model="formData.name"
              :disabled="handle == 'view'"
              placeholder="请输入活动名称"
            />
          </a-form-model-item>
          <a-form-model-item prop="endTime">
            <template slot="label">
              <span style="color: red">*</span>活动时间
            </template>
            <a-date-picker
              style="width: 200px"
              allow-clear
              v-model="formData.startTime"
              :disabled="handle == 'view'"
              :disabled-date="disabledStartDate"
              show-time
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="请选择开始时间"
              @openChange="handleStartOpenChange"
            />
            <span class="form-components-center">至</span>
            <a-date-picker
              style="width: 200px"
              allow-clear
              v-model="formData.endTime"
              :disabled="handle == 'view'"
              :disabled-date="disabledEndDate"
              show-time
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="请选择结束时间"
              :open="endOpen"
              @openChange="handleEndOpenChange"
            />
          </a-form-model-item>
          <a-form-model-item prop="completeNum">
            <template slot="label">
              <span style="color: red">*</span>参团人数
            </template>
            <a-input-number
              allow-clear
              :min="2"
              :max="100"
              style="width: 200px"
              v-model="formData.completeNum"
              :disabled="handle == 'view'"
              placeholder="请输入2-100的数字"
            />
            <span class="form-components-center">人</span>
          </a-form-model-item>
          <a-form-model-item prop="goodsId">
            <template slot="label">
              <span style="color: red">*</span>拼团商品
            </template>
            <a-button v-if="handle != 'view'" type="link" @click="chooseGood"
              >选择商品</a-button
            >
            <a-input
              type="hidden"
              :maxLength="60"
              style="width: 200px"
              v-model="formData.goodsId"
              :disabled="handle == 'view'"
              placeholder="请选择商品"
            />
            <table
              class="form-table"
              style="width: 450px"
              v-if="formData.goodsId"
            >
              <thead>
                <tr>
                  <th>商品名称</th>
                  <!-- <th>规格</th> -->
                  <th>操作</th>
                </tr>
              </thead>
              <tbody>
                <tr>
                  <td>
                    <div class="product_td">
                      <table-img :src="goodsInfo.goodsPicture" />
                      <div class="product_name">{{ goodsInfo.goodsName }}</div>
                    </div>
                  </td>
                  <!-- <td>{{ goodsInfo.goodsName }}</td> -->
                  <td>
                    <a-button
                      type="link"
                      :disabled="handle == 'view'"
                      @click="delChooseGoods"
                      >删除</a-button
                    >
                  </td>
                </tr>
              </tbody>
            </table>
          </a-form-model-item>
          <a-form-model-item v-if="type == 2" prop="prePayPrice">
            <template slot="label">
              <span style="color: red">*</span>预付款
            </template>
            <a-input-number
              allow-clear
              :min="0.01"
              :max="100"
              style="width: 200px"
              v-model="formData.prePayPrice"
              :disabled="handle == 'view'"
              placeholder="请输入预付款"
            />
            <span class="form-components-center">元</span>
          </a-form-model-item>
          <a-form-model-item
            v-if="type == 1 && formData.goodsId"
            prop="goodsSpecList"
          >
            <template slot="label">
              <span style="color: red">*</span>拼团价设置
            </template>
            <table class="form-table" style="width: 450px">
              <thead>
                <tr>
                  <th>选择</th>
                  <th>商品规格</th>
                  <th>原价（元）</th>
                  <th><span class="color_red">*</span>拼团价（元）</th>
                  <th>库存</th>
                </tr>
              </thead>
              <tbody>
                <tr
                  v-for="(item, index) in formData.goodsSpecList"
                  :key="index"
                >
                  <!-- <td>{{ item.availableStatus }}</td> -->
                  <td>
                    <a-switch
                      v-model="item.availableStatus"
                      @change="changeStatus(item, index)"
                      :disabled="handle == 'view'"
                    />
                  </td>
                  <td>{{ item.modelNormName }}</td>
                  <td>{{ item.salePrice }}</td>
                  <td>
                    <a-input-number
                      placeholder="请输入"
                      v-model="item.groupPrice"
                      :disabled="handle == 'view'"
                      :precision="2"
                      :min="0"
                      :max="Number(item.salePrice) || 9999"
                    />
                  </td>
                  <td>{{ item.goodsInventory }}</td>
                </tr>
              </tbody>
            </table>
          </a-form-model-item>
          <a-form-model-item
            v-if="type == 2 && formData.goodsId"
            prop="goodsSpecList"
          >
            <template slot="label">
              <span style="color: red">*</span>拼团价设置
            </template>
            <table class="form-table" style="width: 550px">
              <thead>
                <tr>
                  <th>商品规格</th>
                  <th>原价（元）</th>
                  <th><span class="color_red">*</span>拼团价（元）</th>
                  <th>参团人数/团</th>
                  <th>库存</th>
                  <th>跳动价/件</th>
                </tr>
              </thead>
              <tbody>
                <tr>
                  <td style="width: 120px">
                    <a-select
                      showSearch
                      allowClear
                      v-model="goodsItemInfo.modelNormName"
                      :disabled="handle == 'view'"
                      placeholder="请选择"
                      @change="goodsItemSpecChange"
                    >
                      <a-select-option
                        v-for="(item, index) in goodsItemSpecList"
                        :disabled="handle == 'view'"
                        :key="index"
                        :value="item.modelIds"
                      >
                        {{ item.modelNormName }}
                      </a-select-option>
                    </a-select>
                  </td>
                  <td>{{ goodsItemInfo.salePrice }}</td>
                  <td>
                    <a-input-number
                      placeholder="请输入"
                      v-model="goodsItemInfo.groupPrice"
                      :disabled="handle == 'view'"
                      :precision="2"
                      :min="0"
                      :max="Number(goodsItemInfo.salePrice) || 9999"
                      @change="computedGroupBeatPrice"
                    />
                  </td>
                  <td>{{ formData.completeNum }}</td>
                  <td>{{ goodsItemInfo.goodsInventory }}</td>
                  <td>{{ groupBeatPrice }}</td>
                </tr>
              </tbody>
            </table>
            <template v-if="sameMarketPriceList.length > 0">
              <p class="form-tips" style="margin-top: 10px; font-size: 14px">
                同原价规格商品参与拼团：
              </p>
              <a-checkbox-group
                :disabled="handle == 'view'"
                :value="sameMarketPriceCheckedList"
                @change="checkSameMarketPrice"
              >
                <a-checkbox
                  v-for="(item, index) in sameMarketPriceList"
                  :key="index"
                  :disabled="handle == 'view'"
                  :value="item.id"
                  >{{ item.modelNormName }} 库存{{
                    item.goodsInventory
                  }}</a-checkbox
                >
              </a-checkbox-group>
            </template>
          </a-form-model-item>
          <a-form-model-item prop="validityTime">
            <template slot="label">
              <span style="color: red">*</span>拼团有效期
            </template>
            <a-input
              type="hidden"
              :maxLength="60"
              style="width: 200px"
              v-model="formData.validityTime"
              :disabled="handle == 'view'"
            />
            <a-select
              style="width: 150px"
              allow-clear
              :max-length="20"
              v-model="formData.day"
              :disabled="handle == 'view'"
              placeholder="请选择天数"
              @change="transformValidityTime"
            >
              <a-select-option
                v-for="(n, index) of 31"
                :key="index"
                :value="index"
                >{{ q(index) }}</a-select-option
              >
            </a-select>
            <span class="form-components-center">日</span>
            <a-select
              style="width: 150px"
              allow-clear
              :max-length="20"
              v-model="formData.hour"
              :disabled="handle == 'view'"
              placeholder="请选择小时"
              @change="transformValidityTime"
            >
              <a-select-option
                v-for="(n, index) of 24"
                :key="index"
                :value="index"
                >{{ q(index) }}</a-select-option
              >
            </a-select>
            <span class="form-components-center">时</span>
            <a-select
              style="width: 150px"
              allow-clear
              :max-length="20"
              v-model="formData.minute"
              :disabled="handle == 'view'"
              placeholder="请选择分钟"
              @change="transformValidityTime"
            >
              <a-select-option
                v-for="(n, index) of 60"
                :key="index"
                :value="index"
                >{{ q(index) }}</a-select-option
              >
            </a-select>
            <span class="form-components-center">分</span>
            <p class="form-tips">拼团有效期需在15分钟至30天之间</p>
            <p class="form-tips">
              若设置1日，用户开团后，需要在1日内成团，超时则拼团失败
            </p>
          </a-form-model-item>
          <a-form-model-item v-if="type != 2" prop="discountStatus">
            <template slot="label">
              <span style="color: red">*</span>优惠叠加
            </template>
            <a-radio-group
              :disabled="handle == 'view'"
              v-model="formData.discountStatus"
            >
              <a-radio :style="radioStyle" :value="0"
                >不叠加其他营销活动</a-radio
              >
              <a-radio :style="radioStyle" :value="1">叠加其他营销活动</a-radio>
            </a-radio-group>
          </a-form-model-item>
          <a-form-model-item label="拼团规则说明" prop="description">
            <div class="rule">
              <a-textarea
                style="width: 500px"
                :maxLength="300"
                :auto-size="{ minRows: 3, maxRows: 10 }"
                v-model="formData.description"
                :disabled="handle == 'view'"
                placeholder=""
              />
              <span class="limitWords" v-if="formData.description"
                >{{ formData.description.length || 0 }}/300</span
              >
              <span class="limitWords" v-else>0/300</span>
            </div>
          </a-form-model-item>

          <div class="form-title">高级设置：</div>
          <a-form-model-item v-if="type == 2" label="发起人" prop="createType">
            <a-radio-group
              :disabled="handle == 'view'"
              v-model="formData.createType"
            >
              <a-radio :value="1">用户发起</a-radio>
              <a-radio :value="2">商家发起</a-radio>
            </a-radio-group>
            <p class="form-tips">
              选择商家发起，在设置活动时间内自动发起，用户只可进行参团。
            </p>
          </a-form-model-item>

          <a-form-model-item style="margin: 0" prop="limitBuyStatus">
            <template slot="label">
              <span style="color: red">*</span>限购规则
            </template>
            <a-radio-group
              :disabled="handle == 'view'"
              v-model="formData.limitBuyStatus"
            >
              <a-radio :value="1">限购</a-radio>
              <a-radio :value="0">不限购</a-radio>
            </a-radio-group>
          </a-form-model-item>

          <template v-if="formData.limitBuyStatus == 1">
            <a-form-model-item
              style="margin: 0"
              label=""
              prop="limitBuyCountNum"
            >
              <a-row>
                <a-col :span="5"></a-col>
                <a-col :span="19">
                  <a-checkbox
                    :disabled="handle == 'view'"
                    v-model="formData.limitBuyCountStatusBool"
                  >
                    活动总限购
                    <a-input-number
                      allow-clear
                      :min="1"
                      style="width: 100px"
                      v-model="formData.limitBuyCountNum"
                      :disabled="handle == 'view'"
                      placeholder="请输入"
                    />
                    <span class="form-components-center">件/人</span>
                  </a-checkbox>
                </a-col>
              </a-row>
            </a-form-model-item>
            <a-form-model-item label="" prop="limitBuyOrderNum">
              <a-row>
                <a-col :span="5"></a-col>
                <a-col :span="19">
                  <a-checkbox
                    :disabled="handle == 'view'"
                    v-model="formData.limitBuyOrderStatusBool"
                  >
                    每单限购
                    <a-input-number
                      allow-clear
                      :min="1"
                      :max="
                        formData.limitBuyCountStatusBool
                          ? formData.limitBuyCountNum
                          : 99
                      "
                      style="width: 100px"
                      v-model="formData.limitBuyOrderNum"
                      :disabled="handle == 'view'"
                      placeholder="请输入"
                    />
                    <span class="form-components-center">件/人</span>
                  </a-checkbox>
                </a-col>
              </a-row>
            </a-form-model-item>
          </template>
          <a-form-model-item label="凑团" prop="recommendGroupStatusBool">
            <a-switch
              checked-children="开启"
              un-checked-children="关闭"
              v-model="formData.recommendGroupStatusBool"
              :disabled="handle == 'view'"
            />
            <p class="form-tips">
              开启凑团后，活动商品详情页展示未成团的团列表，买家可以任选一个团参团，若关闭则只能开团。
            </p>
          </a-form-model-item>
          <a-form-model-item label="模拟成团" prop="mockGroupStatusBool">
            <a-switch
              checked-children="开启"
              un-checked-children="关闭"
              v-model="formData.mockGroupStatusBool"
              :disabled="handle == 'view'"
            />
            <p class="form-tips">
              开启模拟成团后，满足条件的团，系统将会模拟“匿名买家”凑满该团，仅需对真实拼团买家发货。
            </p>
            <a-radio-group
              v-if="formData.mockGroupStatusBool"
              v-model="formData.mockGroupType"
              :disabled="handle == 'view'"
            >
              <a-radio :value="1">所有未拼成的团</a-radio>
              <a-radio :value="2"
                >参团人数≥<a-input-number
                  allow-clear
                  :min="1"
                  :max="formData.completeNum - 1"
                  style="width: 100px"
                  v-model="formData.mockGroupLimitNum"
                  :disabled="handle == 'view'"
                  placeholder="请输入"
                />
                <span class="form-components-center">的团</span></a-radio
              >
            </a-radio-group>
          </a-form-model-item>
          <a-form-model-item label="预告" prop="prehotStatusBool">
            <a-switch
              checked-children="开启"
              un-checked-children="关闭"
              v-model="formData.prehotStatusBool"
              :disabled="handle == 'view'"
            />
            <p class="form-tips">
              开启后，商品详情展示未开始的拼团活动，但活动开始前用户无法拼团购买。
            </p>
          </a-form-model-item>
          <a-form-model-item :wrapper-col="{ span: 14, offset: 4 }">
            <a-col :offset="2">
              <a-space>
                <a-button
                  v-if="handle != 'view'"
                  type="primary"
                  @click="submitData()"
                  >提交保存</a-button
                >
                <a-button @click="handleCancel">{{
                  handle != "view" ? "取消" : "返回"
                }}</a-button>
              </a-space>
            </a-col>
          </a-form-model-item>
        </a-form-model>
      </a-col>
    </a-row>

    <chooseProductTable
      ref="chooseProductTable"
      :goodsId="formData.goodsId"
      @getGoodsId="getGoodsId"
    ></chooseProductTable>
  </div>
</template>

<script>
import deepCopy from "@/utils/deepCopy";
import moment from "moment";
import chooseProductTable from "./../components/chooseProductTable.vue";
const formData = {
  type: undefined,
  name: undefined,
  startTime: undefined,
  endTime: undefined,
  goodsId: undefined,
  prePayPrice: undefined,
  goodsSpecList: [],
  groupRuleGoodsSpecList: [],
  validityTime: undefined,
  day: 1,
  hour: 0,
  minute: 0,
  completeNum: undefined,
  discountStatus: 0,
  description: undefined,
  createType: 1,
  limitBuyStatus: 0,
  limitBuyCountStatus: 0,
  limitBuyCountStatusBool: false,
  limitBuyCountNum: 1,
  limitBuyOrderStatus: 0,
  limitBuyOrderStatusBool: false,
  limitBuyOrderNum: 1,
  recommendGroupStatus: 1,
  recommendGroupStatusBool: true,
  mockGroupStatus: 0,
  mockGroupStatusBool: false,
  mockGroupType: 1,
  mockGroupLimitNum: 0,
  prehotStatus: 1,
  prehotStatusBool: true,
};
export default {
  name: "MarketingGroupBargainingPagesForm",
  components: {
    chooseProductTable, // 选择商品弹窗
  },
  computed: {
    // 操作类型
    handle() {
      return this.$route.query.handle || "";
    },
    // 拼团详情id
    id() {
      return this.$route.query.id || "";
    },
    // 拼团类型
    type() {
      return this.$route.query.type || "";
    },
  },
  data() {
    return {
      imgList: [],
      formData,
      // 验证规则
      rules: {},
      // 是否打开endTime
      endOpen: false,
      // 商品信息
      goodsInfo: {},
      // 选中的商品规格信息
      goodsItemInfo: {
        modelNormName: "",
        salePrice: "",
        groupPrice: "",
        goodsInventory: "",
      },
      // 商品规格下拉列表集合
      goodsItemSpecList: [],
      // 同表格选中商品规格原价相同的其他商品规格集合
      sameMarketPriceList: [],
      // 同表格选中商品规格原价相同且被选中参与拼团的其他商品规格id集合
      sameMarketPriceCheckedList: [],
      // 跳动价
      groupBeatPrice: 0,
      radioStyle: {
        display: "block",
        height: "auto",
        lineHeight: "30px",
      },
    };
  },
  created() {
    if (this.id) {
      this.getGroupBargainingInfo(this.id);
    }
    this.resetData();
    // this.typeName(this.type)
    this.transformValidityTime();
  },
  mounted() {},
  methods: {
    moment,
    //重置
    resetData() {
      this.formData = deepCopy(formData);
    },
    //
    typeName(type) {
      switch (type) {
        case "1":
          this.imgList = [
            "~@images/groupBargaining/general_01.png",
            "~@images/groupBargaining/general_02.png",
            "~@images/groupBargaining/general_03.png",
          ];
          break;
        case "2":
          this.imgList = [];
          break;
        default:
          this.imgList = [];
      }
    },
    // 获取拼团详情
    async getGroupBargainingInfo(id) {
      let res = await this.$get(
        "/group/activity/query",
        { id },
        { baseURL: `${location.origin}/goldenhome/ghgroup/admin` }
      );
      if (res && res.returnCode == "1000") {
        if (res.dataInfo) {
          // 拼团有效期转换日时分
          let d = moment.duration(res.dataInfo.validityTime, "seconds");
          res.dataInfo.day = Math.floor(d.asDays()) || 0;
          res.dataInfo.hour = d.hours() || 0;
          res.dataInfo.minute = d.minutes() || 0;
          // 数字转换布尔值
          res.dataInfo.recommendGroupStatus == 1
            ? (res.dataInfo.recommendGroupStatusBool = true)
            : (res.dataInfo.recommendGroupStatusBool = false);
          res.dataInfo.mockGroupStatus == 1
            ? (res.dataInfo.mockGroupStatusBool = true)
            : (res.dataInfo.mockGroupStatusBool = false);
          res.dataInfo.prehotStatus == 1
            ? (res.dataInfo.prehotStatusBool = true)
            : (res.dataInfo.prehotStatusBool = false);
          if (res.dataInfo.limitBuyStatus == 1) {
            res.dataInfo.limitBuyCountStatus == 1
              ? (res.dataInfo.limitBuyCountStatusBool = true)
              : (res.dataInfo.limitBuyCountStatusBool = false);
            res.dataInfo.limitBuyOrderStatus == 1
              ? (res.dataInfo.limitBuyOrderStatusBool = true)
              : (res.dataInfo.limitBuyOrderStatusBool = false);
          }
          res.dataInfo.groupRuleGoodsSpecList =
            res.dataInfo.groupRuleGoodsSpecList.map((item) => {
              if (item.availableStatus == 0) {
                item.availableStatus = false;
                item.groupPrice = "";
              } else {
                item.availableStatus = true;
              }
              return item;
            });
          res.dataInfo.goodsSpecList = res.dataInfo.groupRuleGoodsSpecList;
          if (this.type == 2) {
            res.dataInfo.prePayPrice =
              typeof res.dataInfo.prePayPrice == "string"
                ? (Number(res.dataInfo.prePayPrice) / 100).toFixed(2)
                : (res.dataInfo.prePayPrice / 100).toFixed(2);
          }
          //

          this.formData = res.dataInfo;
          // 获取商品信息
          if (this.handle == "copy") {
            this.formData.goodsSpecList = [];
            this.formData.groupRuleGoodsSpecList = [];
            this.formData.goodsId = "";
            this.formData.startTime = "";
            this.formData.endTime = "";
          } else {
            this.getGoodsSpecList(
              this.formData.goodsId,
              "editGood",
              res.dataInfo.groupRuleGoodsSpecList
            );
          }
        }
      }
    },
    // 补充十位数
    q(num) {
      return num < 10 ? "0" + num : num;
    },
    // 开始时间不能小于当前时间
    disabledStartDate(current) {
      return current < moment().subtract(1, "days");
    },
    // 结束时间不能小于开始时间
    disabledEndDate(current) {
      return current < moment(this.formData.startTime);
    },
    // 是否打开结束时间组件
    handleStartOpenChange(open) {
      if (!open) {
        this.endOpen = true;
      }
    },
    // 结束时间组件
    handleEndOpenChange(open) {
      this.endOpen = open;
    },
    // 选择商品
    chooseGood() {
      this.$refs.chooseProductTable.visible = true;
    },
    // 获取选择商品的id
    getGoodsId(data) {
      this.goodsInfo = data;
      this.formData.goodsId = data.id;
      this.getGoodsSpecList(data.id, "addGood");
    },
    // 获取商品规格集合
    async getGoodsSpecList(id, type, groupRuleGoodsSpecList = []) {
      let res = await this.$get("/goods/query", {
        id,
      });
      if (res && res.returnCode == "1000") {
        let dataInfo = res.dataInfo || {};
        let _this = this;
        this.goodsInfo = dataInfo;
        let goodsSpecList = dataInfo.goodsSpecList;
        if (dataInfo.goodsModel == 1) {
          // 统一规格
          dataInfo.goodsSpecList[0].modelIds = "";
          dataInfo.goodsSpecList[0].modelNormName = "统一规格";
          dataInfo.goodsSpecList[0].salePrice =
            typeof dataInfo.goodsSpecList[0].salePrice == "string"
              ? (Number(dataInfo.goodsSpecList[0].salePrice) / 100).toFixed(2)
              : (dataInfo.goodsSpecList[0].salePrice / 100).toFixed(2);
        } else if (dataInfo.goodsModel == 2) {
          // 多规格
          for (let i = 0; i < goodsSpecList.length; i++) {
            goodsSpecList[i].modelIds = goodsSpecList[i].modelIds;
            goodsSpecList[i].salePrice =
              typeof goodsSpecList[i].salePrice == "string"
                ? (Number(goodsSpecList[i].salePrice) / 100).toFixed(2)
                : (goodsSpecList[i].salePrice / 100).toFixed(2);
            let ids = goodsSpecList[i].modelIds.split(",");
            let nameArr = [];
            for (let j = 0; j < ids.length; j++) {
              let name = await _this.getModelNormName(ids[j]);
              nameArr.push(name);
            }
            goodsSpecList[i].modelNormName = nameArr.join(",");
          }
        }
        if (type == "addGood") {
          // 不同拼团类型
          if (this.type == 1) {
            this.formData.goodsSpecList = dataInfo.goodsSpecList.map((item) => {
              item.availableStatus = true;
              return item;
            });
            console.log(this.formData, "3333333333");
          } else if (this.type == 2) {
            this.goodsItemSpecList = dataInfo.goodsSpecList;
            if (dataInfo.goodsModel == 1) {
              let res = dataInfo.goodsSpecList[0];
              this.goodsItemInfo = {
                id: res.id,
                modelIds: res.modelIds,
                modelNormName: res.modelNormName,
                salePrice: res.salePrice,
                groupPrice: res.groupPrice,
                goodsInventory: res.goodsInventory,
              };
            }
          }
        } else {
          if (this.type == 1) {
            for (let i = 0; i < groupRuleGoodsSpecList.length; i++) {
              let res = dataInfo.goodsSpecList.filter(
                (goodsSpec) =>
                  goodsSpec.id == groupRuleGoodsSpecList[i].goodsSpecId
              )[0];
              groupRuleGoodsSpecList[i].id = res.id;
              groupRuleGoodsSpecList[i].modelIds = res.modelIds;
              groupRuleGoodsSpecList[i].modelNormName = res.modelNormName;
              groupRuleGoodsSpecList[i].salePrice = res.salePrice;
              groupRuleGoodsSpecList[i].groupPrice =
                typeof groupRuleGoodsSpecList[i].groupPrice == "string"
                  ? groupRuleGoodsSpecList[i].groupPrice
                    ? (
                        Number(groupRuleGoodsSpecList[i].groupPrice) / 100
                      ).toFixed(2)
                    : ""
                  : (groupRuleGoodsSpecList[i].groupPrice / 100).toFixed(2);
              groupRuleGoodsSpecList[i].goodsInventory = res.goodsInventory;
            }
            this.formData.goodsSpecList = groupRuleGoodsSpecList;
          } else if (this.type == 2) {
            this.goodsItemSpecList = dataInfo.goodsSpecList;
            if (dataInfo.goodsModel == 1) {
              let res = dataInfo.goodsSpecList[0];
              this.goodsItemInfo = {
                id: res.id,
                modelIds: res.modelIds,
                modelNormName: res.modelNormName,
                salePrice: res.salePrice,
                groupPrice:
                  typeof groupRuleGoodsSpecList[0].groupPrice == "string"
                    ? (
                        Number(groupRuleGoodsSpecList[0].groupPrice) / 100
                      ).toFixed(2)
                    : (groupRuleGoodsSpecList[0].groupPrice / 100).toFixed(2),
                goodsInventory: res.goodsInventory,
              };
            } else if (dataInfo.goodsModel == 2) {
              let res = dataInfo.goodsSpecList.filter(
                (goodsSpec) =>
                  goodsSpec.id == groupRuleGoodsSpecList[0].goodsSpecId
              )[0];
              this.goodsItemInfo = {
                id: res.id,
                modelIds: res.modelIds,
                modelNormName: res.modelNormName,
                salePrice: res.salePrice,
                groupPrice:
                  typeof groupRuleGoodsSpecList[0].groupPrice == "string"
                    ? (
                        Number(groupRuleGoodsSpecList[0].groupPrice) / 100
                      ).toFixed(2)
                    : (groupRuleGoodsSpecList[0].groupPrice / 100).toFixed(2),
                goodsInventory: res.goodsInventory,
              };
              this.sameMarketPriceList = dataInfo.goodsSpecList.filter(
                (item) => item.salePrice == res.salePrice
              );
              this.sameMarketPriceCheckedList = [];
              groupRuleGoodsSpecList.forEach((item) => {
                _this.sameMarketPriceCheckedList.push(item.goodsSpecId);
              });
            }
            // groupRuleGoodsSpecList
            this.computedGroupBeatPrice();
          }
        }
      }
    },
    // 获取商品所有规格名称
    async getModelNormName(id) {
      let res = await this.$get(
        "/goods/modelnorm/id",
        {
          id,
        },
        false,
        true
      );
      if (res && res.returnCode == "1000") {
        return res.dataInfo.normName || "";
      }
    },
    // 删除商品
    delChooseGoods() {
      this.goodsInfo = {};
      this.formData.goodsId = "";
    },
    // 选择某一商品规格
    goodsItemSpecChange(val) {
      this.formData.goodsSpecList = [];
      this.sameMarketPriceList = [];
      if (val) {
        let res = this.goodsItemSpecList.filter(
          (item) => item.modelIds == val
        )[0];
        this.goodsItemInfo = {
          id: res.id,
          modelIds: res.modelIds,
          modelNormName: res.modelNormName,
          salePrice: res.salePrice,
          groupPrice: res.groupPrice,
          goodsInventory: res.goodsInventory,
        };
        this.formData.goodsSpecList.push(this.goodsItemInfo);
        this.sameMarketPriceList = this.goodsItemSpecList.filter(
          (item) => item.salePrice == this.goodsItemInfo.salePrice
        );
      }
    },
    // 选中 同表格选中商品规格原价相同的其他商品规格
    checkSameMarketPrice(val) {
      this.sameMarketPriceCheckedList = val;
    },
    // 计算跳动价 公式（商品单买价-拼团价）/（参团数量/团（人））
    computedGroupBeatPrice() {
      if (!this.formData.completeNum) {
        this.$message.error("请先输入参团人数！");
        this.goodsItemInfo.groupPrice = 0;
        return;
      }
      if (this.goodsItemInfo.modelNormName == "") {
        this.$message.error("请先选择商品规格！");
        this.goodsItemInfo.groupPrice = 0;
        return;
      }
      this.groupBeatPrice =
        "￥ " +
        (
          (this.goodsItemInfo.salePrice - this.goodsItemInfo.groupPrice) /
          this.formData.completeNum
        ).toFixed(2);
    },
    // 转换拼团有效期
    transformValidityTime() {
      this.formData.validityTime =
        (this.formData.day || 0) * 24 * 3600 +
        (this.formData.hour || 0) * 3600 +
        (this.formData.minute || 0) * 60;
    },
    // 返回拼团列表
    back() {
      this.$router.push({
        name: "MarketingGroupBargaining",
        query: {
          type: this.type,
        },
      });
    },
    handleCancel() {
      console.log("取消");
      this.back();
    },
    async submitData() {
      // 验证活动名称
      if (!this.formData.name) {
        return this.$message.error("请输入活动名称");
      }
      // 验证活动时间
      if (!this.formData.startTime) {
        return this.$message.error("请选择活动开始时间");
      }
      if (
        moment(this.formData.startTime).unix() <
        moment().subtract(1, "days").unix()
      ) {
        return this.$message.error("活动开始时间不能小于当前时间");
      }
      if (!this.formData.endTime) {
        return this.$message.error("请选择活动结束时间");
      }
      if (
        moment(this.formData.startTime).unix() >
        moment(this.formData.endTime).unix()
      ) {
        return this.$message.error("活动结束时间不能小于活动开始时间");
      }
      // 验证参团人数
      if (!this.formData.completeNum) {
        return this.$message.error("请输入参团人数");
      }
      // 验证拼团商品
      if (!this.formData.goodsId) {
        return this.$message.error("请选择拼团商品");
      }
      // 验证所有规格是否设置价格
      if (this.type == 1) {
        let goodsSpecListPriceArr = [];
        let chooseGoodsList = [];
        this.formData.goodsSpecList.forEach((item) => {
          if (item.groupPrice && item.availableStatus == true) {
            goodsSpecListPriceArr.push(item.groupPrice);
          }
          if (item.availableStatus == true) {
            chooseGoodsList.push(item);
          }
        });
        if (goodsSpecListPriceArr.length < chooseGoodsList.length) {
          return this.$message.error("请为所选规格商品设置拼团价格");
        }
      } else if (this.type == 2) {
        if (!this.goodsItemInfo.id) {
          return this.$message.error("请选择规格");
        }
        if (!this.goodsItemInfo.groupPrice) {
          return this.$message.error("请设置拼团价格");
        }
        // 验证预付款
        if (!this.formData.prePayPrice) {
          return this.$message.error("请输入预付款");
        }
        if (this.formData.prePayPrice > this.goodsItemInfo.groupPrice) {
          return this.$message.error("预付款不能大于拼团价格");
        }
      }
      // 验证拼团有效期
      if (!this.formData.validityTime) {
        return this.$message.error("请设置拼团有效期");
      }
      if (
        this.formData.validityTime < 15 * 60 ||
        this.formData.validityTime > 30 * 24 * 3600
      ) {
        return this.$message.error("拼团有效期为15分钟-30天");
      }
      // 验证优惠叠加
      if (
        this.formData.discountStatus === "" ||
        this.formData.discountStatus === undefined ||
        this.formData.discountStatus === null
      ) {
        return this.$message.error("请选择优惠叠加");
      }
      // 验证限购时的条件
      if (
        this.formData.limitBuyStatus === "" ||
        this.formData.limitBuyStatus === undefined ||
        this.formData.limitBuyStatus === null
      ) {
        return this.$message.error("请选择限购规则");
      }
      if (
        this.formData.limitBuyStatus == 1 &&
        !this.formData.limitBuyCountStatusBool &&
        !this.formData.limitBuyOrderStatusBool
      ) {
        return this.$message.error("请至少选择一条规则");
      }
      if (
        this.formData.limitBuyStatus == 1 &&
        this.formData.limitBuyCountStatusBool &&
        !this.formData.limitBuyCountNum
      ) {
        return this.$message.error("请输入活动总限购数量");
      }
      if (
        this.formData.limitBuyStatus == 1 &&
        this.formData.limitBuyOrderStatusBool &&
        !this.formData.limitBuyOrderNum
      ) {
        return this.$message.error("请输入每单限购数量");
      }
      // 验证模拟拼团开启的条件
      if (
        this.formData.mockGroupStatusBool &&
        this.formData.mockGroupType == 2 &&
        !this.formData.mockGroupLimitNum
      ) {
        return this.$message.error("请输入模拟成团最低参团人数");
      }
      // 验证至少选择一项商品规格
      if (this.type == 1) {
        let num = 0;
        this.formData.goodsSpecList.forEach((item) => {
          if (item.availableStatus == 1) {
            num++;
          }
        });
        if (num == 0) {
          return this.$message.error("请少选择一项商品规格");
        }
      }
      this.formData.type = this.type;
      let _this = this;
      // 精简去除冗余信息 价格单位转为 分
      if (this.type == 1) {
        this.formData.groupRuleGoodsSpecList = [];
        this.formData.goodsSpecList.forEach((item) => {
          let flag = {
            goodsSpecId: item.id || item.goodsSpecId,
            groupPrice:
              _this.type == 1
                ? item.availableStatus == true
                  ? Math.round(item.groupPrice * 10 * 10)
                  : ""
                : Math.round(_this.goodsItemInfo.groupPrice),
            availableStatus: item.availableStatus == true ? 1 : 0,
          };
          if (flag.availableStatus != 1) delete flag.groupPrice;
          _this.formData.groupRuleGoodsSpecList.push(flag);
        });
      } else if (this.type == 2) {
        // 规则拼团时，同选中商品规格原价相同的其他商品规格放入
        _this.formData.groupRuleGoodsSpecList = [];
        let chooseGoodsSpec = {
          goodsSpecId: _this.goodsItemInfo.id,
          groupPrice: Math.round(_this.goodsItemInfo.groupPrice * 10 * 10),
        };
        _this.formData.groupRuleGoodsSpecList.push(chooseGoodsSpec);
        this.sameMarketPriceCheckedList.forEach((id) => {
          let res = _this.goodsItemSpecList.filter((item) => item.id == id)[0];
          let sameMarketPriceGoodsSpec = {
            goodsSpecId: res.id,
            groupPrice: Math.round(_this.goodsItemInfo.groupPrice * 10 * 10),
          };
          _this.formData.groupRuleGoodsSpecList.push(sameMarketPriceGoodsSpec);
        });
      }
      if (this.formData.prePayPrice) {
        this.formData.prePayPrice = Math.round(
          this.formData.prePayPrice * 10 * 10
        );
      }
      // 布尔值转换数字
      this.formData.recommendGroupStatusBool
        ? (this.formData.recommendGroupStatus = 1)
        : (this.formData.recommendGroupStatus = 0);
      this.formData.mockGroupStatusBool
        ? (this.formData.mockGroupStatus = 1)
        : (this.formData.mockGroupStatus = 0);
      this.formData.prehotStatusBool
        ? (this.formData.prehotStatus = 1)
        : (this.formData.prehotStatus = 0);
      if (this.formData.limitBuyStatus == 1) {
        this.formData.limitBuyCountStatusBool
          ? (this.formData.limitBuyCountStatus = 1)
          : (this.formData.limitBuyCountStatus = 0);
        this.formData.limitBuyOrderStatusBool
          ? (this.formData.limitBuyOrderStatus = 1)
          : (this.formData.limitBuyOrderStatus = 0);
      }
      console.log(this.formData, "3333333333");
      let url = "";
      switch (this.handle) {
        case "add":
          url = "/group/activity/add";
          break;
        case "copy":
          url = "/group/activity/add";
          break;
        case "edit":
          url = "/group/activity/update";
          break;
      }
      let res = await this.$post(url, this.formData, {
        baseURL: `${location.origin}/goldenhome/ghgroup/admin`,
      });
      if (res && res.returnCode == "1000") {
        this.back();
        return this.$message.success("拼团设置成功！");
      } else {
        return this.$message.error("拼团设置失败！");
      }
    },
    changeStatus(item, index) {
      this.$set(this.formData.goodsSpecList, index, item);
    },
  },
};
</script>

<style lang="less" scoped>
.group-bargaining {
  .group-bargaining-carousel {
    margin: 0 20px;
    padding: 5px;
    height: 90vh;
    border: 1px solid #666;
    border-radius: 10px;
    overflow: hidden;
    img {
      width: 100%;
    }
  }
}
.product_td {
  display: flex;
  align-items: center;
  justify-content: center;
  .product_name {
    margin-left: 6px;
  }
}
.rule {
  position: relative;
  width: 500px;
  .limitWords {
    position: absolute;
    right: 6px;
    bottom: -7px;
    font-size: 10px;
    color: #ccc;
  }
}
</style>
